<?php

namespace app\admin\controller\vppz;

//use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Hospital extends Base
{

    /**
     * Hospital模型对象
     * @var \app\admin\model\vppz\Hospital
     */
    protected $model = null;

	protected $searchFields = ['id','name','area.name','rank','label'];
	protected $multiFields = ['use_switch'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vppz\Hospital;
		// 给数据附加当前appid，appid由Base负责解析
		$this->model::event('before_insert', function ($row){
			$row->app_id=$this->app_id;
		});
        $config = \think\App::initCommon();
		$this->model::event('before_insert', function ($row){return $this->beforeSave($row);});
		$this->model::event('before_update', function ($row){return $this->beforeSave($row);});
        $this->assign('hospital_level',$config['hospital_level']);
        $this->assign('hospital_label',$config['hospital_label']);

    }

	// 处理前端输入的城市，分为三段存储
	protected function beforeSave($row){
		if(in_array($this->request->action(),['add','edit'])){
			$city = explode('/',$row->city);
			if(count($city)!=3){
				//$this->error('请选择到区');
				//echo '测试';
				exception('所在区域请选择区县');
				return false;
			}
			$row->province=$city[0];
			$row->city=$city[1];
			$row->district=$city[2];
		}
	}



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;

        $config = \think\App::initCommon();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

			$adminAreasWhere=$this->adminAreasWhere('area_id');

            $list = $this->model
                    ->with(['area'])
                    ->where('is_local','=',2)
                    ->where('is_kuajing','=',2)
                    ->where($where)->where($adminAreasWhere)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->rank = $config['hospital_level'][$row->rank]??'三级';
                $row->label = $config['hospital_label'][$row->label]??'综合医院';
                $row->getRelation('area')->visible(['name']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

		//$areas = $this->adminAreas();
		//var_dump($areas);
		//var_dump([5,4]);


        return $this->view->fetch();
    }


    protected function filter(&$query)
    {
        // 添加性别筛选条件
        if ($this->request->has('rank')) {
            $rank = $this->request->param('rank');
            if ($rank !== '') {
                $query->where('rank', $rank);
            }
        }
        if ($this->request->has('label')) {
            $label = $this->request->param('label');
            if ($label !== '') {
                $query->where('label', $label);
            }
        }
    }

    /**
     * 服务设置
     */
    public function services()
    {
		$ids = input('ids');
        $hospital = $this->model->get(['id' => $ids]);
        if (!$hospital) {
            $this->error(__('No Results were found'));
        }

		$HospitalServiceModel = new \app\admin\model\vppz\HospitalService;

		if ($this->request->isAjax()) {
			$services = input('services/a');

			$hss=array();
			if(count($services)>0){
				foreach($services as $k=>$v){
					if(isset($v['use_switch']) && $v['use_switch']==1){
						if($v['price']<=0){
							$this->error('开启的服务需设置价格（大于0）');
						}
						$hss[]=array(
							'app_id'=>$this->app_id,
							'area_id'=>$hospital['area_id'],
							'hospital_id'=>$hospital['id'],
							'service_id'=>$k,
							'price'=>$v['price'],
							'use_switch'=>$v['use_switch']
						);
					}
				}
			}

			// 对医院服务进行全删全插
			$HospitalServiceModel->where(['app_id'=>$this->app_id,'hospital_id'=>$hospital['id']])->delete();
			$HospitalServiceModel->saveAll($hss);

			$this->success("保存成功");
		}else{

			/**
			$services = Db::name('vppz_service')->field('id,code,name,logo_image,intro,price')->where(['use_switch'=>1])->order('weigh', 'desc')->select();

			$hss = Db::name('vppz_hospital_service')->field('service_id,price,use_switch')->where(['app_id'=>$this->app_id,'hospital_id'=>$hospital['id']])->select();

			// 根据医院设置，覆盖服务
			for($i=0;$i<count($services);$i++){
				for($j=0;$j<count($hss);$j++){
					if($services[$i]['id']==$hss[$j]['service_id']){
						$services[$i]['_hospital']=$hss[$j];


					}

				}
			}
			**/



			$ServiceModel = new \app\admin\model\vppz\Service;
			$services = $ServiceModel->field('id,code,name,logo_image,intro,price')->where(['app_id'=>$this->app_id,'use_switch'=>1])->order('weigh', 'desc')->select();

			$hss = $HospitalServiceModel->field('service_id,price,use_switch')->where(['app_id'=>$this->app_id,'hospital_id'=>$hospital['id']])->select();

			// 根据医院设置，覆盖服务
			for($i=0;$i<count($services);$i++){
				for($j=0;$j<count($hss);$j++){
					if($services[$i]['id']==$hss[$j]['service_id']){
						$services[$i]['_hospital']=$hss[$j];

					}

				}
			}


			$this->view->assign("services", $services);
			return $this->view->fetch();
		}
    }


}
